package com.wejoy.video.middle.station.data.util;

import com.wejoy.video.middle.station.data.enums.dict.EnumGlobalContentAction;
import com.wejoy.video.middle.station.data.enums.dict.EnumGlobalContentType;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 *
 *
 * @author: admin
 * @time: 2022/9/16 12:05
 */
public class AppLinkUtil {
    private final static Logger logger = LoggerFactory.getLogger(AppLinkUtil.class);

    /**
     * 构造内链
     * @param action
     * @param enumGlobalContentType
     * @param args
     * @return
     */
    public static String buildAppLink(EnumGlobalContentAction action, EnumGlobalContentType enumGlobalContentType, String... args) {
        if (enumGlobalContentType.getIndexTab()) {
            action = EnumGlobalContentAction.SWITCH_TAB;
        }
        // 内链就直接返回填写的内容
        if (enumGlobalContentType.getCode().equals(EnumGlobalContentType.INNER_PROTOCOL.getCode())) {
            return String.format("%s", args);
        }
        // 如果是外链需要对地址进行编码
        if (EnumGlobalContentType.WEBVIEW.equals(enumGlobalContentType)) {
            try {
                args[0] = URLEncoder.encode(args[0], "utf-8");
            } catch (UnsupportedEncodingException e) {
                logger.info(e.getMessage(), e);
                throw new BusinessException("URL编码异常");
            }
        }
        String url = action.getUrl() + enumGlobalContentType.getUrl();
        url = String.format(url, args);
        return url;
    }

    public static String buildMpLink(EnumGlobalContentAction action, EnumGlobalContentType enumGlobalContentType, String... args) {
        if (enumGlobalContentType.getIndexTab()) {
            action = EnumGlobalContentAction.SWITCH_TAB;
        }
        // 内链就直接返回填写的内容
        if (enumGlobalContentType.getCode().equals(EnumGlobalContentType.INNER_PROTOCOL.getCode())) {
            return String.format("%s", args);
        }
        // 如果是外链需要对地址进行编码
        if (EnumGlobalContentType.WEBVIEW.equals(enumGlobalContentType)) {
            try {
                if (StringUtils.isNotBlank(args[0])) {
                    args[0] = URLEncoder.encode(args[0], "utf-8");
                } else {
                    args[0] = "";
                }
            } catch (UnsupportedEncodingException e) {
                logger.info(e.getMessage(), e);
                throw new BusinessException("URL编码异常");
            }
        }
        String url = action.getUrl() + String.format(enumGlobalContentType.getUrl(), args);
        return url;
    }
}
